package middleware

import (
    {{if eq .isUser true}}"strings"{{end}}
	"{{.projectName}}/tools"
	"github.com/savsgio/atreugo/v11"
	"github.com/atreugo/cors"
)

type Middleware struct {
	Tool *tools.Tools
}

func NewMiddleware() *Middleware {
	return &Middleware{
		Tool: tools.NewTools(),
	}
}

func (m *Middleware)Cors() atreugo.Middleware {
	return cors.New(cors.Config{
			AllowedOrigins:   []string{"*"},
			AllowedHeaders:   []string{"Content-Type", "X-Custom", "Token", "Authorization"},
			AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE"},
			ExposedHeaders:   []string{"Content-Length", "Authorization"},
			AllowCredentials: true,
			AllowMaxAge:      3600,
		})
}

{{- if eq .isUser true}}
// JWTAuthMiddleware 基于JWT的认证中间件
func (m *Middleware) JWTAuthMiddleware(ctx *atreugo.RequestCtx) error{
	// 这里假设Token放在Header的Authorization中，并使用Bearer开头

	if string(ctx.Path()) == "/login/login" || string(ctx.Path()) == "/filed/viewReportById"{
		return ctx.Next()
	}

	//请求头传递token
	authHeader := string(ctx.Request.Header.Peek("Authorization"))
	if authHeader == "" {
		return ctx.JSONResponse(map[string]interface{}{"code": 604, "message": "请求头中auth为空", "data":nil})
	}

	// 按空格分割
	parts := strings.SplitN(authHeader, " ", 2)
	if !(len(parts) == 2 && parts[0] == "Bearer") {
		return ctx.JSONResponse(map[string]interface{}{"code": 604, "message": "请求头中auth格式有误", "data":nil})
	}

	// parts[1]是获取到的tokenString，我们使用之前定义好的解析JWT的函数来解析它
	_, err := m.Tool.ParseToken(parts[1])
	if err != nil {
		return ctx.JSONResponse(map[string]interface{}{"code": 604, "message": err.Error(), "data":nil})
	}
	//fmt.Println("获取到的用户信息：", mc)

	return ctx.Next()
}
{{end}}

